package com.sc.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.springboot.pojo.*;
import com.sc.springboot.service.*;
import com.sc.springboot.util.JwtUtils;
import com.sc.springboot.util.ResponseMsg;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author romeo
 * @since 2025-09-20 03:18:17
 */
@RestController
@RequestMapping("/post")
//帖子
public class PostController {

    @Autowired
    private IPostService postService;
    
    @Autowired
    private IUsersService usersService;

    @Autowired
    private IPostLikeService postLikeService;
    
    @Autowired
    private ICommentService commentService;

    @Autowired
    private IUserFollowService userFollowService;

    @Autowired
    private FavorRecordController favorRecordController;

    @Autowired
    private IFavorRecordService favorRecordService;

    //推荐分页查询
    @RequestMapping("/page")
    public ResponseMsg page(@RequestParam(defaultValue = "1") Integer pageNum,
                            @RequestParam(defaultValue = "5")  Integer pageSize,
                            @RequestParam (defaultValue = "0") Integer typeId,
                            HttpServletRequest request){
        // 从请求头中获取token
        String token = request.getHeader("token");
        Integer currentUserId = null;  // 当前用户ID
        if (token != null && !token.isEmpty()) { // 判断token是否为空
            currentUserId = JwtUtils.getUserIdFromToken(token); // 从token中获取用户ID
        }
        QueryWrapper<Post> queryWrapper = new QueryWrapper<>();
        IPage<Post> page=null;
        //typeId=0代表推荐页面的数据
        if (typeId==0){
            //如果用户为null，则返回热门的帖子
            if (currentUserId==null){
                page=getHotPostsPage(pageNum,pageSize);
            }else {//如果用户不为null，则返回该用户偏好板块的帖子（各一半）
                //查询该用户偏好板块
                QueryWrapper<FavorRecord> favorRecordQueryWrapper = new QueryWrapper<>();
                favorRecordQueryWrapper.eq("user_id",currentUserId);
                List<FavorRecord> favorRecords = favorRecordService.list(favorRecordQueryWrapper); //查询该用户偏好板块
                if (favorRecords.isEmpty()){ // 如果用户没有设置偏好，则返回热门帖子
                    page=getHotPostsPage(pageNum,pageSize);
                }
                // 按照分数降序排序，获取分数最高的两个板块
                favorRecords.sort(Comparator.comparingInt(FavorRecord::getFavorScore).reversed());
                List<Integer> typeIds = favorRecords.stream()
                        .map(FavorRecord::getTypeId)
                        .limit(2)
                        .collect(Collectors.toList());
                //查询偏好板块的帖子
                queryWrapper.in( "type_id", typeIds);
                page = postService.page(new Page<>(pageNum, pageSize), queryWrapper);
            }
        }else {
            queryWrapper.eq("type_id",typeId);
            page = postService.page(new Page<>(pageNum, pageSize), queryWrapper);
        }
        //为每条帖子添加相关的信息
        page=getHotPostsInfo( page,currentUserId);
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS,page);
    }


    //关注页面获取用户关注的用户的帖子
    @RequestMapping("/getHotPosts")
    public ResponseMsg getHotPosts(@RequestParam(defaultValue = "1") Integer pageNum,
                                   @RequestParam(defaultValue = "5")  Integer pageSize,
                                   HttpServletRequest request){
        // 从请求头中获取token
        String token = request.getHeader("token");
        Integer currentUserId = null;  // 当前用户ID
        if (token != null && !token.isEmpty()) { // 判断token是否为空
            currentUserId = JwtUtils.getUserIdFromToken(token); // 从token中获取用户ID
        }
        IPage<Post> page = new Page<>(pageNum, pageSize); // 创建分页对象
        //查询用户关注的用户的id
        QueryWrapper< UserFollow> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",currentUserId);
        List<UserFollow> userFollows = userFollowService.list(queryWrapper);
        List<Integer> followIds = userFollows.stream()
                .map(UserFollow::getFollowId)
                .collect(Collectors.toList());
        if (followIds.isEmpty()){
            page=getHotPostsPage(pageNum,pageSize);
        }
        //存在关注的id，获取用户关注的用户的帖子
        QueryWrapper<Post> postQueryWrapper = new QueryWrapper();
        postQueryWrapper.in( "user_id", followIds);
        page = postService.page(page,postQueryWrapper);
        //获取帖子的相关信息
        page=getHotPostsInfo(page,currentUserId);
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS,page);
    }

    // 公共方法：获取热门帖子
    private IPage<Post> getHotPostsPage(int pageNum, int pageSize) {
        QueryWrapper<Post> hotQuery = new QueryWrapper<>();
        hotQuery.orderByDesc("likes");  // 按点赞数降序排序
        return  postService.page(new Page<>(pageNum, pageSize), hotQuery);
    }
    //获取帖子的相关信息
    private IPage<Post> getHotPostsInfo(IPage<Post> pageinfo,Integer currentUserId) {
        IPage<Post> page =pageinfo;

        // 添加空值检查，防止 NullPointerException
        if (page == null || page.getRecords() == null) {
            return page;
        }

        // 获取评论的数量
        for (Post post : page.getRecords()) {
            post.setCommentCount((int) commentService.count(new QueryWrapper<Comment>().eq("post_id", post.getPostId())));
        }
        // 添加用户信息到每个帖子
        for (Post post : page.getRecords()) {
            Users user = usersService.getById(post.getUserId());
            post.setUsers(user); // 将用户信息设置到Post对象中

            // 检查当前用户是否已点赞该帖子（仅对已登录用户）
            if (currentUserId != null) {
                QueryWrapper<PostLike> likeQuery = new QueryWrapper<>(); // 创建查询条件
                likeQuery.eq("user_id", currentUserId).eq("post_id", post.getPostId()); // 设置查询条件
                PostLike likeRecord = postLikeService.getOne(likeQuery); // 查询点赞记录
                // 添加用户是否点赞的标记
                post.setUserLiked(likeRecord != null); // 将用户是否点赞的标记添加到Post对象中
            } else {
                // 对未登录用户，默认设置为未点赞
                post.setUserLiked(false);
            }
        }
        return page;
    }




    
    // 点赞/取消点赞
    @RequestMapping(value = "/likes", method = RequestMethod.GET)
    public ResponseMsg likes(@RequestParam Integer postId, HttpServletRequest request){
        // 从请求头中获取token
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            return ResponseMsg.getInstance(ResponseMsg.FAIL, "用户未登录");
        }
        
        // 从token中解析用户ID
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if (userId == null) {
            return ResponseMsg.getInstance(ResponseMsg.FAIL, "无效的用户token");
        }
        
        // 检查用户是否已经点赞
        QueryWrapper<PostLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("post_id", postId);
        PostLike likeRecord = postLikeService.getOne(queryWrapper);
        
        Post post = postService.getById(postId);
        boolean isLiked;
        
        if (likeRecord != null) {
            // 用户已点赞，执行取消点赞操作
            postLikeService.remove(queryWrapper);
            post.setLikes(post.getLikes() - 1);
            isLiked = false;
        } else {
            // 用户未点赞，执行点赞操作
            PostLike newLikeRecord = new PostLike();
            newLikeRecord.setUserId(userId);
            newLikeRecord.setPostId(postId);
            newLikeRecord.setStatus(true);
            postLikeService.save(newLikeRecord);
            post.setLikes(post.getLikes() + 1);
            favorRecordController.add(userId, postId,1);
            isLiked = true;
        }
        
        postService.updateById(post);
        
        // 返回操作结果和当前点赞数
        String message = isLiked ? "点赞成功" : "已取消点赞";
        Map<String, Object> result = new HashMap<>(); // 创建结果对象
        result.put("isLiked", isLiked); // 添加点赞状态
        result.put("likes", post.getLikes()); // 添加点赞数
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, message, result);
    }

    //添加帖子
    @RequestMapping("/add")
    public ResponseMsg add(Post post) {
        post.setPostTime(new Date());
        return postService.save(post) ? ResponseMsg.success() : ResponseMsg.getInstance(ResponseMsg.FAIL, "添加失败");
    }

    //获取帖子详情
    @RequestMapping("/get")
    public ResponseMsg get(@RequestParam Integer postId, HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("token");
        Integer currentUserId = null;
        if (token != null && !token.isEmpty()) { // 判断token是否为空
            currentUserId = JwtUtils.getUserIdFromToken(token); // 从token中获取用户ID
        }
        
        Post post = postService.getById(postId);
        if (post == null) {
            return ResponseMsg.getInstance(ResponseMsg.FAIL, "帖子不存在");
        }
        
        // 添加用户信息到帖子
        Users user = usersService.getById(post.getUserId());
        post.setUsers(user); // 将用户信息设置到Post对象中

        // 检查当前用户是否已点赞该帖子（仅对已登录用户）
        if (currentUserId != null) {
            QueryWrapper<PostLike> likeQuery = new QueryWrapper<>(); // 创建查询条件
            likeQuery.eq("user_id", currentUserId).eq("post_id", post.getPostId()); // 设置查询条件
            PostLike likeRecord = postLikeService.getOne(likeQuery); // 查询点赞记录
            // 添加用户是否点赞的标记
            post.setUserLiked(likeRecord != null); // 将用户是否点赞的标记添加到Post对象中
        } else {
            // 对未登录用户，默认设置为未点赞
            post.setUserLiked(false);
        }
        
        // 获取评论数量- 对所有用户都可见
        post.setCommentCount((int) commentService.count(new QueryWrapper<Comment>().eq("post_id", postId)));
        
        // 获取帖子的所有评论
        List<Comment> allComments = commentService.list(new QueryWrapper<Comment>().eq("post_id", postId));
        
        // 为每个评论设置用户信息
        for (Comment comment : allComments) {
            if (comment.getUserId() != null) {
                Users commentUser = usersService.getById(comment.getUserId());
                comment.setUsers(commentUser);
            }
        }
        
        post.setCommentList(allComments); // 将评论列表设置到Post对象中

        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, post);
    }

    //获取帖子评论列表
    @RequestMapping("/getCommentList")
    public ResponseMsg getCommentList(@RequestParam Integer postId) {
        //获取帖子评论列表
        List<Comment> commentList = commentService.list(new QueryWrapper<Comment>().eq("post_id", postId));
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, commentList);
    }


}